@file:Suppress("unused")

package com.hjh.tool.util

import cn.hutool.core.text.CharSequenceUtil
import cn.hutool.core.util.HexUtil
import com.elvishew.xlog.XLog
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelFutureListener
import io.netty.channel.ChannelHandlerContext

/**
 * @author： hjh
 * @createDate： 2024/11/22 15:39
 * @description：
 * @qq： 3472903821
 * @version: 1.0
 */
object NettyUtil {

    private fun addListener(channelFuture: ChannelFuture, data: ByteArray?, mark: String?) {
        channelFuture.addListener(ChannelFutureListener { future: ChannelFuture ->
            val sb = StringBuilder()
            if (CharSequenceUtil.isNotBlank(mark)) {
                sb.append("【").append(mark).append("】")
            }
            if (future.isSuccess) {
                XLog.v("$sb 回写成功>>>> ${HexUtil.encodeHexStr(data)}")
            } else {
                XLog.e("$sb 回写失败>>>> ${HexUtil.encodeHexStr(data)}")
            }
        })
    }

    private fun writeToClient(data: ByteArray?, ctx: ChannelHandlerContext, mark: String?) {
        try {
            // netty需要用ByteBuf传输
            val buffer = Unpooled.buffer()
            // 对接需要16进制
            buffer.writeBytes(data)
            val channelFuture = ctx.writeAndFlush(buffer)
            addListener(channelFuture, data, mark)
        } catch (e: Exception) {
            XLog.e("调用通用writeToClient()异常: ${e.message}")
            e.printStackTrace()
        }
    }

    fun writeToClient(data: String?, ctx: ChannelHandlerContext, mark: String?) {
        try {
            // netty需要用ByteBuf传输
            val buffer = Unpooled.buffer()
            // 对接需要16进制
            buffer.writeBytes(HexUtil.decodeHex(data))
            val channelFuture = ctx.writeAndFlush(buffer)
            addListener(channelFuture, HexUtil.decodeHex(data), mark)
        } catch (e: Exception) {
            XLog.e("调用通用writeToClient()异常: ${e.message}")
            e.printStackTrace()
        }
    }

    fun writeToClient(data: String?, channel: Channel, mark: String?) {
        try {
            // netty需要用ByteBuf传输
            val buffer = Unpooled.buffer()
            // 对接需要16进制
            buffer.writeBytes(HexUtil.decodeHex(data))
            val channelFuture = channel.writeAndFlush(buffer)
            addListener(channelFuture, HexUtil.decodeHex(data), mark)
        } catch (e: Exception) {
            XLog.e("调用通用writeToClient()异常: ${e.message}")
            e.printStackTrace()
        }
    }
}